import { MaterialService } from 'src/app/@core/services/material/material.service';
import { Router } from '@angular/router';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { DialogService } from 'ng-devui/modal';
import { Component } from '@angular/core';
import { EditableTip, FormLayout, TableWidthConfig } from 'ng-devui';
import { SelectTicketsComponent } from './select-tickets/select-tickets.component';
import { SelectInventoryComponent } from 'src/app/@shared/components/select-inventory/select-inventory.component';
import { GetPartsComponent } from './select-part/get-parts/get-parts.component';

@Component({
  selector: 'app-add-picking-list',
  templateUrl: './add-picking-list.component.html',
  styleUrls: ['./add-picking-list.component.scss']
})
export class AddPickingListComponent {
  layoutDirection: FormLayout = FormLayout.Horizontal;
  editableTip = EditableTip.hover;
  jobOrderlssue = {
    jobOrderIssueNum:"",
    issueUserNum:"",
    issueUserName:"",
    issueTime:"",
    auditUserId:0,
    auditUserNum:"",
    auditUserName:"",
    auditTime:"",
    jobOrderProcessId:0,
    items:[
      {
        jobOrderProcessPartId:0,
        jobOrderId:0,
        jobOrderNum:"",
        jobOrderProcessId:0,
        processNum:"",
        processName:"",
        processId:0,
        ProcessNumber:"",
        partId:"",
        partNum:"",
        partName:"",
        partType:"",
        uom:"",
        requiredQuantity:0,
        requiredQuantityUnit:"",
        issuedQuantity:0,
        issuedQuantityUnit:"",
        PreIssuedQuantity:0,
        warehouseId:0,
        warehouseNum:"",
        warehouseName:"",
        positionId:0,
        positionNum:"",
        positionName:"",
        partPositionInventory:0
      }
    ]
  }
  CreatJobOrderIssue:any={}
  info:any = {}
  dataTableOptions={
    columns:[
      {
          field: 'name',
          header: '工单号',
          fieldType: 'text',
      },
      {
        field: 'name',
        header: '工序名称',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料名称',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料单位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '需求数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '已发数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '发料数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '仓库',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '仓位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '仓位数量',
        fieldType: 'text',
      },


    ]
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '100px'
    },
    {
      field:'操作',
      width:'100px'
    },
    {
      field:'工单号',
      width:'100px'
    },
    {
      field:'销售订单号',
      width:'100px'
    },
    {
      field:'销售订单号',
      width:'100px'
    },
    {
      field:'销售订单号',
      width:'100px'
    },
    {
      field:'销售订单号',
      width:'100px'
    },
    {
      field:'产品编码',
      width:'100px'
    },
    {
      field:'规格',
      width:'150px'
    },
    {
      field:'单位',
      width:'150px'
    },
    {
      field:'计划数量',
      width:'150px'
    },
    {
      field:'计划数量',
      width:'100px'
    },



  ];
  msgs: { severity: any; summary: any; content: any; }[];
  constructor(private dialogService:DialogService,private StorehouseService:StorehouseService,private EncodeRulesService:EncodeRulesService,private Router:Router,private MaterialService:MaterialService) {}
  submit($event: any){
    this.CreatJobOrderIssue.jobOrderIssueNum = this.jobOrderlssue.jobOrderIssueNum
    this.CreatJobOrderIssue.creatorName = this.jobOrderlssue.issueUserName
    this.jobOrderlssue.items = Object.values(this.jobOrderlssue.items.reduce((acc, item) => {
      // 创建一个键，该键是所有需要匹配的属性的组合
      let key = `${item.jobOrderProcessPartId}-${item.warehouseId}`;
      if (!acc[key]) {
        // 如果这个键在累加器中不存在，那么添加这个对象
        acc[key] = { ...item };
      } else {
        // 如果这个键在累加器中存在，那么将periodIssuedQuantity相加
        acc[key].PreIssuedQuantity += item.PreIssuedQuantity;
      }
      return acc;
    }, {}));
    this.CreatJobOrderIssue.createJobOrderIssueDetailsDtos = this.jobOrderlssue.items
  .filter(item => item.PreIssuedQuantity != null)
  .map(item => ({
    jobOrderProcessId: item.jobOrderProcessId,
    positionId: item.positionId,
    jobOrderProcessPartId: item.jobOrderProcessPartId,
    periodIssuedQuantity: item.PreIssuedQuantity
  }));
    this.StorehouseService.CreateJobOrderIssue(this.CreatJobOrderIssue).subscribe((res:any)=>{
     this.showToast('success','成功','创建成功')
     setTimeout(() => {
      this.Router.navigate(['/pages/product/product-job-pink'])
     }, 1000);
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }
  cancle(){
    this.Router.navigate(['/pages/product/product-job-pink'])
  }
  ngOnInit(): void {
  const info = localStorage.getItem('userinfo');
   this.EncodeRulesService.GenerateWarehouseCodeRule('生产发料单','生产发料单').subscribe((res:any)=>{
    this.jobOrderlssue.jobOrderIssueNum = res
    })
    const parsedInfo = JSON.parse(info);
    this.jobOrderlssue.issueUserNum = parsedInfo.employeeCode;
    this.jobOrderlssue.issueUserName = parsedInfo.username;
  }
  issuances(dialogtype?: string){
    const results = this.dialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width:'1000px',
      title: '选择工单工序',
      content: SelectTicketsComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if(results.modalContentInstance.getParts){

              this.StorehouseService.GetIssueJobOrderProcessPartsByProcessId(results.modalContentInstance.getParts).subscribe((data:any)=>{
                if(data.items.length==0){
                  this.showToast('warn','提示','所选工单或工序暂无可发物料')
                }
                this.jobOrderlssue.items = data.items
                this.jobOrderlssue.items.forEach((item:any)=>{
                  item.PreIssuedQuantity = item.requirementQuantity-item.issuedQuantity
                  item.warehouseId = item.defaultWarehouseId
                  item.warehouseNum = item.defaultWarehouseNum
                  item.warehouseName = item.defaultWarehouseName
                  item.positionId = item.defaultPositionId
                  item.positionNum = item.defaultPositionNum
                  item.positionName = item.defaultPositionName
                  if (item.positionId == null) {

                    this.StorehouseService.GetIssuedPositionInventoryByPartNum(item.partNum, 1, 999).subscribe((data: any) => {
                        if (data.items && data.items.length > 0) {
                            item.warehouseId = data.items[0].warehouseId;
                            item.warehouseNum = data.items[0].warehouseNum;
                            item.warehouseName = data.items[0].warehouseName;
                            item.positionId = data.items[0].positionId;
                            item.positionNum = data.items[0].positionNum;
                            item.positionName = data.items[0].positionName;
                        }
                    });
                }
                })

              })
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectPart(dialogtype?: string){
    const results = this.dialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width:'1000px',
      title: '选择物料',
      content: GetPartsComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              this.jobOrderlssue.items = results.modalContentInstance.selectData
              this.jobOrderlssue.items.forEach((item:any)=>{
                item.PreIssuedQuantity = item.requirementQuantity-item.issuedQuantity
                item.warehouseId = item.defaultWarehouseId
                item.warehouseNum = item.defaultWarehouseNum
                item.warehouseName = item.defaultWarehouseName
                item.positionId = item.defaultPositionId
                item.positionNum = item.defaultPositionNum
                item.positionName = item.defaultPositionName
                if (item.positionId == null) {
                  this.StorehouseService.GetIssuedPositionInventoryByPartNum(item.partNum, 1, 999).subscribe((data: any) => {
                      if (data.items && data.items.length > 0) {
                          item.warehouseId = data.items[0].warehouseId;
                          item.warehouseNum = data.items[0].warehouseNum;
                          item.warehouseName = data.items[0].warehouseName;
                          item.positionId = data.items[0].positionId;
                          item.positionNum = data.items[0].positionNum;
                          item.positionName = data.items[0].positionName;
                      }
                  });
              }
              })
              this.MaterialService.getPartById(this.jobOrderlssue.items[0].partId).subscribe(
                (data:any)=>{
                  this.jobOrderlssue.items[0].positionId = data.positionID
                  this.StorehouseService.getWarehouseById(data.positionID).subscribe(
                    (data:any)=>{
                      this.jobOrderlssue.items[0].warehouseName = data.warehouseName
                    }
                  )
                  this.StorehouseService.GetPositionById(data.positionID).subscribe(
                    (data:any)=>{
                      this.jobOrderlssue.items[0].positionName = data.positionName
                    }
                  )
                  this.jobOrderlssue.items[0].warehouseId = data.warehouseID
                }
              )
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  SelectStorehouse(rowItem:any,dialogService?:string){
    const results = this.dialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width:'1000px',
      title: '选择仓库',
      data:rowItem,
      content: SelectInventoryComponent,
      dialogtype: dialogService,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              rowItem.warehouseName = results.modalContentInstance.selectData.warehouseName;
              rowItem.warehouseNum = results.modalContentInstance.selectData.warehouseNum;
              rowItem.warehouseId = results.modalContentInstance.selectData.warehouseId;
              rowItem.positionName = results.modalContentInstance.selectData.positionName;
              rowItem.positionNum = results.modalContentInstance.selectData.positionNum;
              rowItem.positionId = results.modalContentInstance.selectData.positionId;
              rowItem.partPositionInventory = results.modalContentInstance.selectData.partPositionInventory;
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  delete(index:number,dialogtype?:string){
    const results = this.dialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width:'400px',
      title: '删除',
      content: '确认删除该条数据吗？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            this.jobOrderlssue.items.splice(index,1)
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }
  apart(index: number) {
    const item = JSON.parse(JSON.stringify(this.jobOrderlssue.items[index])); // 获取索引位置的元素的深拷贝
    item.PreIssuedQuantity = 0; // 将 PreIssuedQuantity 设置为 0
    this.jobOrderlssue.items.splice(index + 1, 0, item); // 将修改后的 item 插入到数组中
  }
  changeQuantity($event:any,index:number){
    if(this.jobOrderlssue.items[index].positionId == null){
      this.showToast('error','失败','请先选择仓库仓位')
      this.jobOrderlssue.items[index].partPositionInventory = 0
      return
    }
  }
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
}
